
exports.listen = function(port){
  var io = require('socket.io').listen(port);
  io.sockets.on('connection', function (socket) {
    initialize(socket);
  });
};

var objects = {};

function initialize(socket){
  
  socket.on('jsr.get', function(id){
    var obj = objects[id];
    if(!obj){
      obj = objects[id] = {};
    }
    
    socket.on('jsr.change.' + id, function(param){
      var name = param.name;
      var value = param.value;
      var o = objects[id];
      if(o[name] != value){
        o[name] = value;      
        socket.broadcast.emit('jsr.onchange.' + id, {
          name:name, 
          value:value
        });
      }
    });
    
    socket.on('jsr.notify.' + id, function(){
      socket.broadcast.emit('jsr.onnotify.' + id);
    });
    
    socket.emit('jsr.get.' + id, obj);
  });
  
 
}